import 'package:flutter/material.dart';
import 'package:flutter_study/flutter/_19%E5%B0%8F%E7%BB%84%E4%BB%B6/post.dart';

void main() => runApp(MyApp());

/// 带分页表格控件
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '分页表格',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        splashColor: Colors.transparent,
      ),
      home: HomePage(),
    );
  }
}

// 定义数据源
class PostDataSource extends DataTableSource {
  List<Post> postList = posts;

  int _selectedCount = 0;

  @override
  DataRow getRow(int index) {
    Post post = postList[index];
    return DataRow.byIndex(index: index, cells: [
      DataCell(Text(post.title)),
      DataCell(Text(post.author)),
      DataCell(Image.network(post.imageUrl)),
    ]);
  }

  @override
  bool get isRowCountApproximate => false;

  @override
  int get rowCount => postList.length;

  @override
  int get selectedRowCount => _selectedCount;
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _sortColumnIndex;

  bool _sortAscending = true;

  @override
  Widget build(BuildContext context) {
    final PostDataSource _dataSource = PostDataSource();

    return Scaffold(
        appBar: AppBar(
          title: Text('分页表格'),
        ),
        body: Container(
          padding: EdgeInsets.all(12.0),
          child: ListView(
            children: [
              PaginatedDataTable(
                header: Text("Post"),
                // 每页显示的条目
                rowsPerPage: 5,
                source: _dataSource,
                // 按照哪一行排序，以及排序规则
                sortColumnIndex: _sortColumnIndex,
                sortAscending: _sortAscending,
                columns: [
                  DataColumn(
                      label: Text('Title'),
                      onSort: (index, ascending) {
                        setState(() {
                          _sortColumnIndex = index;
                          _sortAscending = ascending;

                          // 排序
                          posts.sort((a, b) {
                            if (!ascending) {
                              // 交换顺序
                              final c = a;
                              a = b;
                              b = c;
                            }
                            return a.title.length.compareTo(b.title.length);
                          });
                        });
                      }),
                  DataColumn(label: Text('Author')),
                  DataColumn(label: Text('Image')),
                ],
              ),
            ],
          ),
        ));
  }
}
